package com.bangwz.bio;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端
 * 
 * @author venus
 * @E-mail: dongyz@xcbobo.com
 * @qq: 416331017
 * @version 创建时间：2018年4月7日 下午9:55:08
 *
 */
public class Server {

	public static void start() throws IOException {
		ServerSocket server = new ServerSocket(9527);
		System.err.println("服务器启动了。。。");
		// 循环accept，监听
		while (true) {
			Socket client = server.accept();
			new Thread(new hander(client)).start();
		}
	}
}

class hander implements Runnable {

	private Socket socket;

	public hander(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			InputStream inputStream = socket.getInputStream();

			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

			StringBuilder sb = new StringBuilder();
			String reslut;
			while ((reslut = reader.readLine()) != null) {
				sb.append(reslut);
			}
			System.err.println("服务器收到消息。" + sb.toString());
			OutputStream outputStream = socket.getOutputStream();
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
			writer.write("你好，client");
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
